/**
 * IPS Social Suite 4
 * (c) 2013 Invision Power Services - http://www.invisionpower.com
 *
 * toc.js - TOC JS controller
 *
 * Author: Invisionify.com
 */
;( function($, _, undefined){
	"use strict";

	ips.controller.register('fxpages.toc', {

		initialize: function () {
			this.setup();
		},

		setup: function () {
          
          var headings = this.scope.find("h1,h2,h3,h4,h5,h6");
          headings.each( function (j) {
              var anchor = $('<a>');
              anchor.attr('id', 'toc'+j);
              anchor.insertBefore (this);
              //$( this ).attr('id', 'toc'+j);
		  });
          
			var ul = $('<nav>');
            ul.addClass('tocMenu ipsPad ipsSpacer_bottom ipsType_richText');
            ul.append("<div class='ipsType_sectionHead ipsSpacer_bottom'>"+ips.getString('fxpages_toc')+"</div>");
            for(var i = 1; i <= 6; i++){
              var hs = this.scope.find('h' + i);
              if(hs.length){
                ul[0].childHeaders = hs
                ul[0].childHeaderLevel = i;
                break;
              }
            }
            var rootUl = ul;
            
            while(ul.length) {
              var nextUl = $();
              ul.each(function(){
                 var innerUl = this;
                 var n = this.childHeaderLevel;
                 innerUl.childHeaders.each(function(i,elem){
                    var childUl = $('<ul>').append('<li><a href="#' + $(elem).prev().attr('id') + '">' + $(elem).html() +'</a></li>')
                                           .appendTo(innerUl);
                    childUl[0].childHeaders = $(this).nextUntil('h' + n)
                                                     .filter('h' + (n+1));
                    childUl[0].childHeaderLevel = n + 1;            
                    nextUl = nextUl.add(childUl);
                 });                            
              });
              ul = nextUl;   
            }

            this.scope.prepend(rootUl);
 		}
	});
}(jQuery, _));

        